package cn.imvc.app.models;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import com.opensymphony.xwork2.ActionContext;

import cn.imvc.app.entities.Dealer;
import cn.imvc.app.entities.DealerApply;
import cn.imvc.app.entities.DealerLevel;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.DealerApplyRepository;
import cn.imvc.app.repositories.DealerRepository;
import cn.imvc.app.repositories.MemberRepository;
import cn.imvc.data.domain.ViewRequest;
/**
 * 
 * @author wujx
 * @time 2016年7月22日
 *
 */
@Service
public class DealerApplyModelImpl implements DealerApplyModel {
	@Autowired
	private DealerApplyRepository dealerApplyRepository;
	@Autowired
	private MemberRepository memberRepository;
	@Autowired
	private DealerRepository dealerRepository;

	public Page<DealerApply> findAll(ViewRequest viewRequest) {
		
		return dealerApplyRepository.findAll("distinct d","DealerApply d left join d.member m left join d.member.dealer.dealerLevel l",viewRequest);
	}

	public DealerApply getOne(int id) {
		return dealerApplyRepository.getOne(id);
	}
	
	/**
	 * 审批通过后向dealer表中插入一条分销商记录
	 */
	public void updateApproved(int id) {
		DealerApply dealerApply = dealerApplyRepository.getOne(id);
		dealerApply.setState((byte) 1);
		dealerApplyRepository.saveAndFlush(dealerApply);
		Member member = dealerApply.getMember();
		Dealer dealer = member.getDealer();
		if(dealer == null){
	    dealer = new Dealer();
	    dealer.setCreatedAt(new Date());
		}
		dealer.setMember(memberRepository.getOne(dealerApply.getMember().getId()));
		dealer.setName(dealerApply.getMember().getName());
		dealer.setDealerLevel(dealerApply.getDealerLevel());
		dealer.setUpdatedAt(new Date());
		dealerRepository.saveAndFlush(dealer);
	}

	public void updateNotApproved(int id) {
		DealerApply dealerApply = dealerApplyRepository.getOne(id);
		dealerApply.setState((byte) 2);
		dealerApplyRepository.saveAndFlush(dealerApply);
	}

}
